package com.kaily.timemanager.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.app.common.util.Logger;
import com.kaily.timemanager.obj.Task;
import com.kaily.timemanager.obj.TaskClass;
import com.kaily.timemanager.obj.Think;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhoulikai on 17/2/27.
 */

public class AppDBManager implements AppDbInterface.ITask, AppDbInterface.ITaskClass, AppDbInterface.IThink {

    private static final String TAG = "AppCipDBManager";
    // 静态引用
    private volatile static AppDBManager mInstance;
    // DatabaseHelper
    private AppBaseDBHelper dbHelper;

    private AppDBManager(Context context) {
        dbHelper = new AppBaseDBHelper(context.getApplicationContext());
    }

    /**
     * 获取单例引用
     *
     * @param context
     * @return
     */
    public static AppDBManager getInstance(Context context) {
        AppDBManager inst = mInstance;
        if (inst == null) {
            synchronized (AppDBManager.class) {
                inst = mInstance;
                if (inst == null) {
                    inst = new AppDBManager(context);
                    mInstance = inst;
                }
            }
        }
        return inst;
    }

    @Override
    public long addTask(Task task) {

        long result = 0;
        //必要字段检查
        if (task == null || TextUtils.isEmpty(task.getTaskClassId()) || TextUtils.isEmpty(task.getTaskName()) || TextUtils.isEmpty(task.getTaskParentId())) {
            return result;
        }
        //获取写数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //生成要修改或者插入的键值
        ContentValues cv = new ContentValues();
        cv.put(AppDatabase.TaskEntry.task_do_status, task.getTaskDoStatus());
        cv.put(AppDatabase.TaskEntry.task_end_time, task.getTaskEndTime());
        cv.put(AppDatabase.TaskEntry.task_class_id, task.getTaskClassId());
        cv.put(AppDatabase.TaskEntry.task_extra, task.getTaskExtra());
        cv.put(AppDatabase.TaskEntry.task_flag, task.getTaskFlag());

        cv.put(AppDatabase.TaskEntry.task_label, task.getTaskLabel());
        cv.put(AppDatabase.TaskEntry.task_parent_id, task.getTaskParentId());
        cv.put(AppDatabase.TaskEntry.task_priority, task.getTaskPriority());
        cv.put(AppDatabase.TaskEntry.task_remind_status, task.getTaskRemindStatus());
        cv.put(AppDatabase.TaskEntry.task_start_time, task.getTaskStartTime());

        cv.put(AppDatabase.TaskEntry.task_name, task.getTaskName());


        // insert 操作
        result = db.insert(AppDatabase.TaskEntry.TABLE_NAME, null, cv);
        //关闭数据库
        db.close();
        return result;
    }

    @Override
    public List<Task> getTasks(String taskClassId, String taskParentId) {
        List<Task> tasks = new ArrayList<>();
        //指定要查询的是哪几列数据
        String[] columns = {AppDatabase.TaskEntry._ID, AppDatabase.TaskEntry.task_do_status,
                AppDatabase.TaskEntry.task_end_time, AppDatabase.TaskEntry.task_class_id, AppDatabase.TaskEntry.task_extra, AppDatabase.TaskEntry.task_flag,
                AppDatabase.TaskEntry.task_label, AppDatabase.TaskEntry.task_parent_id, AppDatabase.TaskEntry.task_priority, AppDatabase.TaskEntry.task_remind_status,
                AppDatabase.TaskEntry.task_start_time, AppDatabase.TaskEntry.task_name
        };
        //获取可读数据库
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        //查询数据库
        Cursor cursor = null;
        try {

            cursor = db.query(AppDatabase.TaskEntry.TABLE_NAME, columns, AppDatabase.TaskEntry.task_class_id + "=? and " + AppDatabase.TaskEntry.task_parent_id + "=?", new String[]{taskClassId, taskParentId}, null, null, null);
            while (cursor.moveToNext()) {
                Task task = new Task();

                task.setTaskClassId(cursor.getString(cursor.getColumnIndex(AppDatabase.TaskEntry.task_class_id)));
                task.setTaskId(cursor.getString(cursor.getColumnIndex(AppDatabase.TaskEntry._ID)));
                task.setTaskDoStatus(cursor.getInt(cursor.getColumnIndex(AppDatabase.TaskEntry.task_do_status)));
                task.setTaskEndTime(cursor.getLong(cursor.getColumnIndex(AppDatabase.TaskEntry.task_end_time)));
                task.setTaskExtra(cursor.getString(cursor.getColumnIndex(AppDatabase.TaskEntry.task_extra)));

                task.setTaskFlag(cursor.getString(cursor.getColumnIndex(AppDatabase.TaskEntry.task_flag)));
                task.setTaskLabel(cursor.getString(cursor.getColumnIndex(AppDatabase.TaskEntry.task_label)));
                task.setTaskName(cursor.getString(cursor.getColumnIndex(AppDatabase.TaskEntry.task_name)));
                task.setTaskStartTime(cursor.getLong(cursor.getColumnIndex(AppDatabase.TaskEntry.task_start_time)));
                task.setTaskRemindStatus(cursor.getInt(cursor.getColumnIndex(AppDatabase.TaskEntry.task_remind_status)));

                task.setTaskParentId(cursor.getString(cursor.getColumnIndex(AppDatabase.TaskEntry.task_parent_id)));
                task.setTaskPriority(cursor.getInt(cursor.getColumnIndex(AppDatabase.TaskEntry.task_priority)));

                //使用递归 递归获取到子任务
                task.setTasks(getTasks(taskClassId, task.getTaskId()));
                tasks.add(task);
            }

        } catch (SQLException e) {
            Logger.d(TAG, "queryDatas" + e.toString());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                //关闭数据库
                db.close();
            }

        }


        return tasks;
    }

    @Override
    public long updateTask(Task task) {
        long result = 0;
        //必要字段检查
        if (task == null || TextUtils.isEmpty(task.getTaskId()) || TextUtils.isEmpty(task.getTaskClassId()) || TextUtils.isEmpty(task.getTaskName()) || TextUtils.isEmpty(task.getTaskParentId())) {
            return result;
        }

        //获取写数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //生成要修改或者插入的键值
        ContentValues cv = new ContentValues();
        cv.put(AppDatabase.TaskEntry.task_do_status, task.getTaskDoStatus());
        cv.put(AppDatabase.TaskEntry.task_end_time, task.getTaskEndTime());
        cv.put(AppDatabase.TaskEntry.task_class_id, task.getTaskClassId());
        cv.put(AppDatabase.TaskEntry.task_extra, task.getTaskExtra());
        cv.put(AppDatabase.TaskEntry.task_flag, task.getTaskFlag());

        cv.put(AppDatabase.TaskEntry.task_label, task.getTaskLabel());
        cv.put(AppDatabase.TaskEntry.task_parent_id, task.getTaskParentId());
        cv.put(AppDatabase.TaskEntry.task_priority, task.getTaskPriority());
        cv.put(AppDatabase.TaskEntry.task_remind_status, task.getTaskRemindStatus());
        cv.put(AppDatabase.TaskEntry.task_start_time, task.getTaskStartTime());

        cv.put(AppDatabase.TaskEntry.task_name, task.getTaskName());

        // update 操作
        result = db.update(AppDatabase.TaskEntry.TABLE_NAME, cv, AppDatabase.TaskEntry._ID + "=?", new String[]{task.getTaskId()});
        //关闭数据库
        db.close();

        return result;
    }

    @Override
    public long deleteTask(Task task) {
        long result = 0;
        if (task == null || TextUtils.isEmpty(task.getTaskId())) {
            return result;
        }

        //获取写数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        // delete 操作
        result = db.delete(AppDatabase.TaskEntry.TABLE_NAME, AppDatabase.TaskEntry._ID + "=?", new String[]{task.getTaskId()});
        //关闭数据库
        db.close();
        return result;
    }

    @Override
    public long deleteTask(TaskClass taskClass) {
        long result = 0;
        if (taskClass == null || TextUtils.isEmpty(taskClass.getTaskClassId())) {
            return result;
        }

        //获取写数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        // delete 操作
        result = db.delete(AppDatabase.TaskEntry.TABLE_NAME, AppDatabase.TaskEntry.task_class_id + "=?", new String[]{taskClass.getTaskClassId()});
        //关闭数据库
        db.close();
        return result;
    }

    @Override
    public long addTaskClass(TaskClass taskClass) {
        long result = 0;
        if (taskClass == null || TextUtils.isEmpty(taskClass.getTaskClassName())) {
            return result;
        }
        //获取写数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //生成要修改或者插入的键值
        ContentValues cv = new ContentValues();
        cv.put(AppDatabase.TaskClassEntry.task_class_name, taskClass.getTaskClassName());
        // insert 操作
        result = db.insert(AppDatabase.TaskClassEntry.TABLE_NAME, null, cv);
        //关闭数据库
        db.close();
        return result;
    }

    @Override
    public long deleteTaksClass(TaskClass taskClass) {
        long result = 0;
        if (taskClass == null || TextUtils.isEmpty(taskClass.getTaskClassId())) {
            return result;
        }

        //获取写数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        // delete 操作
        result = db.delete(AppDatabase.TaskClassEntry.TABLE_NAME, AppDatabase.TaskClassEntry._ID + "=?", new String[]{taskClass.getTaskClassId()});

        //删除该类型的任务的所有的任务
        if (result > 0) {
            result = deleteTask(taskClass);
        }

        //关闭数据库
        db.close();
        return result;
    }

    @Override
    public long updateTaskClass(TaskClass taskClass) {
        long result = 0;
        if (taskClass == null || TextUtils.isEmpty(taskClass.getTaskClassName()) || TextUtils.isEmpty(taskClass.getTaskClassId())) {
            return result;
        }

        //生成要修改或者插入的键值
        ContentValues cv = new ContentValues();
        cv.put(AppDatabase.TaskClassEntry.task_class_name, taskClass.getTaskClassName());
        //获取写数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        // update 操作
        result = db.update(AppDatabase.TaskClassEntry.TABLE_NAME, cv, AppDatabase.TaskClassEntry._ID + "=?", new String[]{taskClass.getTaskClassId()});
        //关闭数据库
        db.close();

        return result;
    }

    @Override
    public List<TaskClass> getTaskClasses() {
        List<TaskClass> taskClasses = new ArrayList<>();
        //指定要查询的是哪几列数据
        String[] columns = {AppDatabase.TaskClassEntry._ID, AppDatabase.TaskClassEntry.task_class_name};
        //获取可读数据库
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        //查询数据库
        Cursor cursor = null;
        try {

            cursor = db.query(AppDatabase.TaskClassEntry.TABLE_NAME, columns, null, null, null, null, null);
            while (cursor.moveToNext()) {
                TaskClass taskClass = new TaskClass();
                taskClass.setTaskClassId(cursor.getString(cursor.getColumnIndex(AppDatabase.TaskClassEntry._ID)));
                taskClass.setTaskClassName(cursor.getString(cursor.getColumnIndex(AppDatabase.TaskClassEntry.task_class_name)));
                taskClass.setTasks(getTasks(taskClass.getTaskClassId(), "0"));
                taskClasses.add(taskClass);
            }

        } catch (SQLException e) {
            Logger.d(TAG, "queryDatas" + e.toString());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                //关闭数据库
                db.close();
            }

        }


        return taskClasses;
    }

    @Override
    public long addThink(Think think) {
        long result = 0;
        if (think == null || TextUtils.isEmpty(think.getThinkTitle()) || TextUtils.isEmpty(think.getThinkContent())) {
            return result;
        }

        //获取写数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //生成要修改或者插入的键值
        ContentValues cv = new ContentValues();
        cv.put(AppDatabase.ThinkEntry.think_title, think.getThinkTitle());
        cv.put(AppDatabase.ThinkEntry.think_content, think.getThinkContent());
        cv.put(AppDatabase.ThinkEntry.think_create_time, think.getThinkCreateTime());
        // insert 操作
        result = db.insert(AppDatabase.ThinkEntry.TABLE_NAME, null, cv);
        //关闭数据库
        db.close();
        return result;
    }

    @Override
    public List<Think> getThinks() {
        List<Think> thinks = new ArrayList<>();
        //指定要查询的是哪几列数据
        String[] columns = {AppDatabase.ThinkEntry._ID, AppDatabase.ThinkEntry.think_title, AppDatabase.ThinkEntry.think_content, AppDatabase.ThinkEntry.think_create_time};
        //获取可读数据库
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        //查询数据库
        Cursor cursor = null;
        try {

            cursor = db.query(AppDatabase.ThinkEntry.TABLE_NAME, columns, null, null, null, null, null);
            while (cursor.moveToNext()) {
                Think taskClass = new Think();
                taskClass.setThinkId(cursor.getString(cursor.getColumnIndex(AppDatabase.ThinkEntry._ID)));
                taskClass.setThinkContent(cursor.getString(cursor.getColumnIndex(AppDatabase.ThinkEntry.think_content)));
                taskClass.setThinkTitle(cursor.getString(cursor.getColumnIndex(AppDatabase.ThinkEntry.think_title)));
                taskClass.setThinkCreateTime(cursor.getLong(cursor.getColumnIndex(AppDatabase.ThinkEntry.think_create_time)));
                thinks.add(taskClass);
            }

        } catch (SQLException e) {
            Logger.d(TAG, "queryDatas" + e.toString());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                //关闭数据库
                db.close();
            }

        }


        return thinks;
    }

    @Override
    public long deleteThink(Think think) {

        long result = 0;
        if (think == null || TextUtils.isEmpty(think.getThinkId())) {
            return result;
        }

        //获取写数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        // delete 操作
        result = db.delete(AppDatabase.ThinkEntry.TABLE_NAME, AppDatabase.ThinkEntry._ID + "=?", new String[]{think.getThinkId()});
        //关闭数据库
        db.close();
        return result;
    }

    @Override
    public long updateThink(Think think) {
        long result = 0;
        if (think == null || TextUtils.isEmpty(think.getThinkId()) || TextUtils.isEmpty(think.getThinkContent()) || TextUtils.isEmpty(think.getThinkTitle())) {
            return result;
        }

        //生成要修改或者插入的键值
        ContentValues cv = new ContentValues();
        cv.put(AppDatabase.ThinkEntry.think_title, think.getThinkTitle());
        cv.put(AppDatabase.ThinkEntry.think_content, think.getThinkContent());
        cv.put(AppDatabase.ThinkEntry.think_create_time, think.getThinkCreateTime());
        //获取写数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        // update 操作
        result = db.update(AppDatabase.ThinkEntry.TABLE_NAME, cv, AppDatabase.ThinkEntry._ID + "=?", new String[]{think.getThinkId()});
        //关闭数据库
        db.close();

        return result;
    }
}
